package dynamicProgramming;

/**
 * @program: data_structures_algorithms
 * @description: 动态规划解决01背包问题
 * @author: lld
 * @create: 2020-11-16 19:41
 **/
public class Demo1 {
    public static void main(String[] args) {
        int[] w = {1, 4, 3};//物品的重量
        int[] val = {1500, 3000, 2000};//物品的价值
        int m = 4;//背包容量
        int n = val.length;//物品的个数
        //创建二维数组,v[i][j]表示前i个物品能够装入容量为j的背包的最大价值
        int[][] v = new int[n + 1][m + 1];

        int[][] path = new int[n + 1][m + 1];
        //动态规划,i,j=1代表不处理第一行第一列
        for (int i = 1; i < v.length; i++) {
            for (int j = 1; j < v[i].length; j++) {
                //当放入的容量大于背包容量
                if (w[i - 1] > j) {//由于i从1开始，所以w[i],val[i]变成i-1
                    v[i][j] = v[i - 1][j];
                } else {//当放入的容量小于背包容量
//                    v[i][j]=Math.max(v[i-1][j],val[i-1]+v[i-1][j-w[i-1]]);
                    if (v[i - 1][j] < val[i - 1] + v[i - 1][j - w[i - 1]]) {
                        v[i][j] = val[i - 1] + v[i - 1][j - w[i - 1]];
                        path[i][j] = 1;
                    } else {
                        v[i][j] = v[i - 1][j];
                    }
                }
            }
        }
        //输出
        for (int i = 0; i < v.length; i++) {
            for (int j = 0; j < v[i].length; j++) {
                System.out.printf("%d\t", v[i][j]);
            }
            System.out.println();
        } //输出
        for (int i = 0; i < path.length; i++) {
            for (int j = 0; j < path[i].length; j++) {
                System.out.printf("%d\t", path[i][j]);
            }
            System.out.println();
        }
        //记录哪些商品放入到背包
        int i = path.length - 1;
        int j = path[0].length - 1;
        while (i > 0 && j > 0) {
            if (path[i][j] == 1) {

                System.out.printf("第%d个放入\n", i);
                j -= w[i - 1];//放入一个求背包剩余容量
            }
            i--;
        }
    }
}
